//
//  BLRechargePayViewController.m
//  blanket
//
//  Created by Mac on 2017/12/6.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "BLRechargePayViewController.h"
#import "BLPayModel.h"
@interface BLRechargePayViewController ()
@property(nonatomic, strong) STButton                     *alipayButton;
@property(nonatomic, strong) STButton                     *wechatButton;
@property(nonatomic, strong) NSArray                     *dataSouce;
@end

@implementation BLRechargePayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"支付";
    [self configSubView];
    // Do any additional setup after loading the view.
}
#pragma mark --subView
- (void)configSubView{
    __weak typeof(self) weakSelf =  self;
    self.alipayButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)
                                                     title:nil
                                                titleColor:nil
                                                 titleFont:0
                                              cornerRadius:0
                                           backgroundColor:nil
                                           backgroundImage:nil
                                                     image:[UIImage imageNamed:@"购物未选中"]];
    [self.alipayButton setClicAction:^(UIButton *sender) {
        weakSelf.wechatButton.selected = NO;
        sender.selected = YES;
    }];
    [self.alipayButton setImage:[UIImage imageNamed:@"购物选中"] forState:UIControlStateSelected];
    self.alipayButton.selected = YES;
    self.wechatButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)
                                                  title:nil
                                             titleColor:nil
                                              titleFont:0
                                           cornerRadius:0
                                        backgroundColor:nil
                                        backgroundImage:nil
                                                  image:[UIImage imageNamed:@"购物未选中"]];
    [self.wechatButton setClicAction:^(UIButton *sender) {
        weakSelf.alipayButton.selected = NO;
        sender.selected = YES;
    }];
    [self.wechatButton setImage:[UIImage imageNamed:@"购物选中"] forState:UIControlStateSelected];
    
    STTableEasyModel * model0 = [[STTableEasyModel alloc] initWithTextString:@"支付宝支付" imageName:@"支付宝"];
    model0.accessoryView = self.alipayButton;
    STTableEasyModel * model1 = [[STTableEasyModel alloc] initWithTextString:@"微信支付" imageName:@"微信支付"];
    model1.accessoryView = self.wechatButton;
    self.dataSouce = @[model0,model1];
    [self.tableView reloadData];
    
    
    
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    footer.backgroundColor = self.tableView.backgroundColor;
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,  150, 80, 80)];
    imageView.centerX = UIScreenWidth / 2;
    imageView.image = [UIImage imageNamed:@"底图logo"];
    [footer addSubview:imageView];
    [footer addSubview:imageView];
    self.tableView.tableFooterView = footer;
    
    [self configBootomeView];
}
- (void)configBootomeView{
    __weak typeof(self) weakSelf =  self;
    UIView  * bootomView = [[UIView alloc] initWithFrame:CGRectMake(0, [TMUtils tabbar].top, UIScreenWidth, 49)];
    bootomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bootomView];
    [bootomView st_showTopShadow];
    [bootomView st_showBottomLine];
    NSString * price = self.paramDic[@"price"];
    _moneyStr = price;
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(15, 0, 200, 44)
                                                     text:[NSString stringWithFormat:@"支付:￥%@",_moneyStr]
                                                textColor:BL_redColor
                                                     font:15
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    titleLable.attributedText = [titleLable.text st_convertAttributeStringWithKeyWord:@"支付:" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13],NSForegroundColorAttributeName:BL_firstTextColor}];
    [bootomView addSubview:titleLable];
    
    
   
    
    STButton * confim = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 120, 49)
                                                  title:@"付款"
                                             titleColor:[UIColor whiteColor]
                                              titleFont:15
                                           cornerRadius:0
                                        backgroundColor:KL_BlueBackGroundColor
                                        backgroundImage:nil
                                                  image:nil];
    confim.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [confim setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedConfimButton];
    }];
    confim.right = UIScreenWidth;
    [bootomView addSubview:confim];
    
    
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 60;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    cell.textLabel.textColor = UIColorFromRGBA(0x333333);
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
    cell.detailTextLabel.textColor = UIColorFromRGBA(0x999999);
    
    STTableEasyModel * model = self.dataSouce[indexPath.row];
    cell.imageView.image = model.image;
    cell.textLabel.text = model.textString;
    cell.accessoryView = model.accessoryView;
    cell.accessoryType = UITableViewCellAccessoryNone;
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (void)onSelectedConfimButton{
    if (self.alipayButton.selected) {
        NSLog(@"支付宝支付");
        [self.paramDic setObject:@"2" forKey:@"type"];
    }else{
         NSLog(@"微信支付");
        [self.paramDic setObject:@"3" forKey:@"type"];
    }
    [self sendCommitRequeest];
}
#pragma mark --NetWork Method
- (void)sendPayRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/rechargeAction"];

    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:self.paramDic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSDictionary * dataDic =  responseObject[@"data"];
                                                 NSString * state = self.paramDic[@"state"];
                                                 if ([state isEqualToString:@"3"]) {
                                                     //微信
                                                     PayReq *request = [PayReq new];
                                                     request.nonceStr = dataDic[@"noncestr"];
                                                     request.package = dataDic[@"package"];
                                                     request.partnerId = dataDic[@"partnerid"];
                                                     request.prepayId = dataDic[@"prepayid"];
                                                     request.sign = dataDic[@"sign"];
                                                     request.timeStamp = [dataDic[@"timestamp"] intValue];
                                                     [WXApi sendReq:request];
                                                     
                                                 }else if([state isEqualToString:@"2"]){
                                                     //支付宝
                                                 }

                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendCommitRequeest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/createOrderAction"];
    [self.paramDic setObject:@"1" forKey:@"display"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:self.paramDic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSString * order =  responseObject[@"data"];
                                                 //NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 NSString * type = self.paramDic[@"type"];
                                                 if ([type isEqualToString:@"1"]) {
                                                     [SVProgressHUD showSuccessWithStatus:@"支付成功"];
                                                     [self.tableView.mj_header beginRefreshing];
                                                 }
                                                 if ([type isEqualToString:@"3"]) {
                                                     //微信
                                                     [self wechatPayWithOrder:order];
                                                     
                                                 }else if([type isEqualToString:@"2"]){
                                                     //支付宝
                                                     [self alipayFreshWithOrderId:order];
                                                 }
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)aliPayWithOrder:(NSString*)orderID{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
     [dic setObject:debugToken forKey:@"token"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/aliapyAction"];
    if (orderID.length) {
        [dic setObject:orderID forKey:@"order_no"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSString * alipayStr =  responseObject[@"data"];
                                                 [[AlipaySDK defaultService] payOrder:alipayStr fromScheme:@"blanket" callback:^(NSDictionary *resultDic) {
                                                     NSLog(@"reslut = %@",resultDic);
                                                     //回调在appdelegate 中
                                                 }];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)alipayFreshWithOrderId:(NSString*)orderID{
   
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:debugToken forKey:@"token"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Online/signature"];
//    url = @"http://39.104.78.211/pugai/alipay/signatures_url.php";
    if (orderID.length) {
        [dic setObject:orderID forKey:@"order"];
    }
    if ([STUserManger defult].userID.length) {
         [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSString * alipayStr =  responseObject[@"data"];
                                                 [[AlipaySDK defaultService] payOrder:alipayStr fromScheme:@"blanket" callback:^(NSDictionary *resultDic) {
                                                     NSLog(@"reslut = %@",resultDic);
                                                     //回调在appdelegate 中
                                                 }];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)wechatPayWithOrder:(NSString*)order{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    // [dic setObject:debugToken forKey:@"token"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Weipay/weixin_pay"];
    if (order.length) {
        [dic setObject:order forKey:@"order"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSDictionary * dataDic =  responseObject[@"data"];
                                                 //NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 
                                                 PayReq *request = [PayReq new];
                                                 request.nonceStr = dataDic[@"noncestr"];
                                                 request.package = dataDic[@"package"];
                                                 request.partnerId = dataDic[@"partnerid"];
                                                 request.prepayId = dataDic[@"prepayid"];
                                                 request.sign = dataDic[@"sign"];
                                                 request.timeStamp = [dataDic[@"timestamp"] intValue];
                                                 [WXApi sendReq:request];
                                                 [self.tableView.mj_header beginRefreshing];
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end
